﻿

namespace FileStrider
{
    using System;
    using System.IO;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;

    class Helper
    {
        // Colors to display folders and files with custom attributes
        public static readonly SolidColorBrush HiddenFileColor = new SolidColorBrush(Colors.Gray);
        public static readonly SolidColorBrush CompressedFileColor = new SolidColorBrush(Colors.Blue);
        public static readonly SolidColorBrush EncryptedFileColor = new SolidColorBrush(Colors.Green);

        /// <summary>
        /// Counts total size of files in the folder
        /// </summary>
        /// <param name="folder">Folder name to check</param>
        /// <param name="recursive">Scan also nested folders</param>
        /// <returns></returns>
        public static long GetFolderSize(string folder, bool recursive)
        {
            long size = 0;
            DirectoryInfo directoryInfo = new DirectoryInfo(folder);
            foreach (var file in directoryInfo.GetFiles())
            {
                size += file.Length / 1024 / 1024;
            }
            if (recursive)
            {
                foreach (var dir in directoryInfo.GetDirectories())
                {
                    GetFolderSize(dir.FullName, true);
                }
            }
            return size;
        }

        /// <summary>
        /// Retrives System Icon for the specified Drive
        /// </summary>
        /// <param name="drive">Drive</param>
        /// <returns>BitmapImage</returns>
        public static BitmapImage GetDriveIcon(string drive)
        {
            MemoryStream strm = new MemoryStream();
            try
            {
                ShellAPI.GetIcon(drive, Win32.SHGFI.SHGFI_ICON | Win32.SHGFI.SHGFI_ICON).ToBitmap().Save(strm, System.Drawing.Imaging.ImageFormat.Png);
            }
            catch (Exception)
            {

                throw new IconReadException();
            }

            BitmapImage bmpImage = new BitmapImage();
            bmpImage.BeginInit();
            bmpImage.StreamSource = strm;
            bmpImage.EndInit();

            return bmpImage;
        }

        public class IconReadException : ApplicationException
        {
            public override string Message
            {
                get
                {
                    return "Unable to extract icon. " + base.Message;
                }
            }
        }
    }
}
